﻿using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Web;

namespace DBA.Common
{
    public class CookieHelper
    {
        public static void AddCookie(HttpCookie cookie)
        {
            HttpContext.Current.Response.Cookies.Add(cookie);
        }

        public static void ClearCookie()
        {
            HttpContext.Current.Response.Cookies.Clear();
        }

        public static void ClearCookie(string cookieName)
        {
            HttpCookie cookie = GetCookie(cookieName);
            if (cookie != null)
            {
                cookie.Expires = DateTime.Now.AddDays(-1.0);
                AddCookie(cookie);
            }
        }

        public static bool Exist(string cookieName)
        {
            return (GetCookie(cookieName) != null);
        }

        public static HttpCookie GetCookie(string cookieName)
        {
            return HttpContext.Current.Request.Cookies[CookieNamePrefix + cookieName];
        }

        public static T GetObject<T>(string cookieName, bool encode = true)
        {
            return ReflectorHelper.GetObject<T>(ReflectorHelper.GetKeyValuListFromCookies(cookieName, encode));
        }

        public static void UpdateCookie(string cookieName, string key, string value)
        {
            HttpContext.Current.Response.Cookies[cookieName][key] = value;
        }

        public static void WriteObject(object input, string cookieName, DateTime expireTime, bool encode = true)
        {
            
            HttpCookie cookie = new HttpCookie(cookieName)
            {
                Expires = expireTime
            };
            foreach (KeyValuePair<string, object> pair in ReflectorHelper.GetKeyValueListFromObject(input))
            {
                cookie[pair.Key] = encode ? UtilsHelper.Encode(pair.Value.ToString()) : pair.Value.ToString();
            }
            AddCookie(cookie);
        }

        public static string CookieNamePrefix
        {
            get
            {
                return "";
            }
        }
    }
}

